﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Com.WebApi.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

namespace Com.WebApi.Controllers
{
    [Produces("application/json")]
    [Route("api/Token")]
    public class TokenController : Controller
    {
        public IConfiguration Configuration;
        public TokenController(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public  IActionResult Token(string username, string password)
        {
            if (!ModelState.IsValid||string.IsNullOrWhiteSpace(username)|| string.IsNullOrWhiteSpace(password))
            {
                return BadRequest();
            }
            var id = 1;
            var claims = new Claim[] { new Claim(ClaimTypes.Name,username),new Claim(ClaimTypes.NameIdentifier,id.ToString()),new Claim(ClaimTypes.Role,"vip") };

            var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["JwtSecurityKey"]));
            var expires= DateTime.Now.AddHours(20);
            var token=new JwtSecurityToken(
                    issuer: Configuration["issuer"],
                    audience: Configuration["audience"],
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: expires,
                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

            string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            return Ok(new { accessToken=jwtToken,expires= expires.Ticks});
        }
    }
}